package com.shenmazong.servertalkadmin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shenmazong.pojo.TbAdmin;
import com.shenmazong.servertalkadmin.mapper.TbAdminMapper;
import com.shenmazong.servertalkadmin.service.TbAdminService;
import com.shenmazong.utils.JwtTokenUtils;
import com.shenmazong.utils.ResponseResult;
import com.shenmazong.utils.StringTools;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class TbAdminServiceImpl implements TbAdminService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    TbAdminMapper tbAdminMapper;

    /**
     * TODO 添加管理员
     * @param userName
     * @param userPass
     * @return
     */
    @Override
    public ResponseResult addAdminUser(String userName, String userPass) {

        ResponseResult result = ResponseResult.SUCCESS();
        HashMap<String, Object> resultMap = new HashMap<>();

        //-- 检查用户是否存在
        TbAdmin admin = tbAdminMapper.selectOne(new QueryWrapper<TbAdmin>()
                .eq("admin_name", userName)
                .last("limit 1"));
        if(admin != null) {
            result.setSuccess(false);
            result.setCode(-1);
            result.setMessage("管理员已存在");
            return result;
        }

        //--1 用户名
        admin = new TbAdmin();
        admin.setAdminName(userName);

        //--2 密码
        String salt = StringTools.getRandomString(32);
        admin.setPassSalt(salt);

        // 生成密码(123456.oieuroqeuro)
        String password = userPass + "." +salt;
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        log.info("pass:"+md5Password);
        admin.setAdminPass(md5Password);

        tbAdminMapper.insert(admin);
        if(admin.getId() != null) {
            admin.setPassSalt("");
            admin.setAdminPass("");
            resultMap.put("admin", admin);

            result.setResult(resultMap);
            return result;
        }

        result.setSuccess(false);
        result.setCode(-1);
        result.setMessage("管理员添加失败");
        return result;
    }

    /**
     * TODO 删除管理员
     * @param userId
     * @return
     */
    @Override
    public ResponseResult delAdminUser(Integer userId) {
        ResponseResult result = ResponseResult.SUCCESS();
        HashMap<String, Object> resultMap = new HashMap<>();

        //--1 判断用户是否存在
        TbAdmin admin = tbAdminMapper.selectById(userId);
        if(admin == null) {
//            result.setSuccess(false);
//            result.setCode(-1);
//            result.setMessage("管理员不存在");
            result.setFailMessage("管理员不存在");
            return result;
        }

        if(!admin.getAdminStatus().equals(0)) {
            result.setSuccess(false);
            result.setCode(-1);
            result.setMessage("管理员已删除");
            return result;
        }

        //--2 设置删除标志
        admin.setAdminStatus(1);
        tbAdminMapper.updateById(admin);

        resultMap.put("admin", admin);
        result.setResult(resultMap);

        return result;
    }

    /**
     * TODO 修改管理密码
     * @param userId
     * @param userPass
     * @return
     */
    @Override
    public ResponseResult setAdminPass(Integer userId, String userPass) {
        ResponseResult result = ResponseResult.SUCCESS();
        HashMap<String, Object> resultMap = new HashMap<>();

        //--1 判断用户是否存在
        TbAdmin admin = tbAdminMapper.selectById(userId);
        if(admin == null) {
            result.setSuccess(false);
            result.setCode(-1);
            result.setMessage("管理员不存在");
            return result;
        }

        if(!admin.getAdminStatus().equals(0)) {
            result.setSuccess(false);
            result.setCode(-1);
            result.setMessage("管理员已删除");
            return result;
        }

        //--2 修改密码
        // 生成密码(123456.oieuroqeuro)
        String password = userPass + "." +admin.getPassSalt();
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        log.info("pass:"+md5Password);
        admin.setAdminPass(md5Password);

        tbAdminMapper.updateById(admin);

        resultMap.put("admin", admin);
        result.setResult(resultMap);

        return result;
    }

    /**
     * TODO 管理员登录
     * @param userName
     * @param userPass
     * @return
     */
    @Override
    public ResponseResult doAdminLogin(String userName, String userPass) {
        ResponseResult result = ResponseResult.SUCCESS();
        HashMap<String, Object> resultMap = new HashMap<>();

        //--1 查询用户
        TbAdmin admin = tbAdminMapper.selectOne(new QueryWrapper<TbAdmin>()
                .eq("admin_name", userName)
                .eq("admin_status", 0)
                .last("limit 1"));
        if(admin == null) {
            result.setSuccess(false);
            result.setCode(-1);
            result.setMessage("管理员不存在");
            return result;
        }

        //--2 判断密码
        String password = userPass + "." +admin.getPassSalt();
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        if(!admin.getAdminPass().equals(md5Password)) {
            result.setSuccess(false);
            result.setCode(-1);
            result.setMessage("管理员密码不正确");
            return result;
        }

        //--3 生成token
        String token = JwtTokenUtils.makeToken(admin.getId(), admin.getAdminName(), "admin");
        resultMap.put("admin", admin);
        resultMap.put("token", token);

        result.setResult(resultMap);

        //--4 单点登录
        String key = "admin_token_" + admin.getId();
        redisTemplate.opsForValue().set(key, token, 1, TimeUnit.DAYS);

        return result;
    }

    /**
     * TODO getAdminList 获取管理员密码
     * @return
     */
    @Override
    public ResponseResult getAdminList() {
        ResponseResult result = ResponseResult.SUCCESS();
        HashMap<String, Object> resultMap = new HashMap<>();

        List<TbAdmin> admins = tbAdminMapper.selectList(
                new QueryWrapper<TbAdmin>()
                        .select("id,admin_name,admin_status,create_time")
                        .orderByAsc("id"));
        resultMap.put("admins", admins);

        result.setResult(resultMap);

        return result;
    }
}
